//
//  HRLikeMeViewController.m
//  SpeedDating
//
//  Created by ISU1 on 17/1/4.
//  Copyright © 2017年 isu. All rights reserved.
//31.9571270000,118.8260800000 31.9580540000,118.8258870000

#import "FriendLikeMeViewController.h"
#import "HRLikeMeTableViewCell.h"
#import "MessageModelManager.h"
#import "HomeStrangCollionViewController.h"
#import "HQConversationViewController.h"
//礼物添加好友
#import "FriendLikeGitfAddController.h"

@interface FriendLikeMeViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *dataSource;

@property (nonatomic, assign) NSInteger pageNum;

@property (nonatomic, strong) UILabel *wooCountLab;

@end

@implementation FriendLikeMeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    

    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 64)];
    headerView.backgroundColor = RGB(246, 246, 246);
    
    UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(KScreenWidth/4, 8, 40, 40)];
    imgView.image = [UIImage imageNamed:@"who_like_number_icon"];
    imgView.contentMode = UIViewContentModeScaleAspectFill;
    [headerView addSubview:imgView];
    

    
    
    self.wooCountLab = [[UILabel alloc] init];
    self.wooCountLab.frame =  CGRectMake(imgView.right+30, 15, KScreenWidth, 34);
    self.wooCountLab.textAlignment = NSTextAlignmentLeft;

    self.wooCountLab.font = FontP(15);
    [headerView addSubview:self.wooCountLab];
    
    if (!_tableView) {
        _tableView = [[UITableView alloc] init];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.frame = CGRectMake(0, 0,KScreenWidth, KScreenHeight-64);
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.tableHeaderView = headerView;
    }
    [self.view addSubview:_tableView];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _dataSource = @[].mutableCopy;
    _pageNum = 1;
    [self wooCountRequest];
    [self sendRequest];
}

- (void)wooCountRequest{

    
    [HQHttpManager mfWithUid:[HQHttpManager getUserId] successBlock:^(BOOL isSuccess, NSDictionary *resultDic) {
        if (isSuccess) {
            NSDictionary *dict = resultDic;
//            NSNumber *count = dict[@"wooCount"];
 
            NSString *str = [NSString stringWithFormat:@"有%@人喜欢你",_likeNumber.stringValue];
            
            NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc]initWithString:str];
            [attributedStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(1,str.length-4)];
            self.wooCountLab.attributedText = attributedStr;
            
        }
        
        
    }];

}

- (void)sendRequest {
    [SVProgressHUD showWithStatus:@"加载数据中..."];
    self.view.userInteractionEnabled = NO;
    [HQHttpManager getwhoWooMeListWithUid:[HQHttpManager getUserId] lon:[[NSUserDefaults standardUserDefaults] objectForKey:@"longitude"] lat:[[NSUserDefaults standardUserDefaults] objectForKey:@"latitude"] page:@(_pageNum) successBlock:^(BOOL isSuccess, NSDictionary *resultDic) {
        [SVProgressHUD dismiss];
        self.view.userInteractionEnabled = YES;
        if (isSuccess) {
            NSArray *array = resultDic[@"res"];
            if (_pageNum == 1) {
                [self.dataSource removeAllObjects];
            }
            if (array.count>0) {
                [self.dataSource addObjectsFromArray:resultDic[@"res"]];
            } else {
                //[self.tableView.mj_footer endRefreshingWithNoMoreData];
                _pageNum--;
            }
            [_tableView reloadData];
        } else {
            _pageNum--;
        }
    }];
}


- (void)backAction {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc]init] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc]init]];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor blackColor], NSFontAttributeName : FontP(18)};
    self.navigationController.navigationBar.barTintColor = Colorbackground;
    [self.navigationController.navigationBar setTranslucent:NO];
    [self setTitle:@"谁喜欢我"];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"清空" style:UIBarButtonItemStylePlain target:self action:@selector(clickRitghButton)];
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [btn setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    btn.frame = CGRectMake(0, 0, 25, 25);
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:btn];

    
    
    
    WEAKSELF
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _pageNum = 1;
        [weakSelf sendRequest];
        [weakSelf.tableView.mj_header endRefreshing];
    }];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        _pageNum++;
        [weakSelf sendRequest];
        [weakSelf.tableView.mj_footer endRefreshing];
    }];
}

- (void)clickRitghButton {
    
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"确定要清空吗" message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *confirAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];

    UIAlertAction *Action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [SVProgressHUD show];

        self.view.userInteractionEnabled = NO;
        WEAKSELF
        [HQHttpManager emptyWooWithUid:[HQHttpManager getUserId] successBlock:^(BOOL isSuccess, NSDictionary *resultDic) {
            [SVProgressHUD dismiss];
            self.view.userInteractionEnabled = YES;
            if (isSuccess) {
                weakSelf.pageNum = 1;
                _likeNumber = 0;
                NSString *str = [NSString stringWithFormat:@"有0人喜欢你"];
                
                NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc]initWithString:str];
                [attributedStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(1,str.length-4)];
                self.wooCountLab.attributedText = attributedStr;
                [weakSelf sendRequest];
                
            }
        }];

    }];
    [alertVC addAction:confirAction];
    [alertVC addAction:Action];

    [self.navigationController presentViewController:alertVC animated:YES completion:nil];

    
   }
#pragma mark ============tabledelegate and datesoure============
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *dic = _dataSource[indexPath.row];
    return [HRLikeMeTableViewCell getHeightWithModel:[HRLikeMeModel getLikeMeModelWithDictionary:dic]];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *dic = _dataSource[indexPath.row];
    HRLikeMeTableViewCell *cell = [HRLikeMeTableViewCell cellWithTableView:tableView indexPath:indexPath];

    
    
    cell.likeButton.tag = indexPath.row + 100;
    cell.refuseButton.tag = indexPath.row + 200;
    cell.headImageButton.tag = indexPath.row + 300;
    [cell.likeButton addTarget:self action:@selector(clickLikeButton:) forControlEvents:UIControlEventTouchUpInside];
    [cell.refuseButton addTarget:self action:@selector(clickRefuseButton:) forControlEvents:UIControlEventTouchUpInside];
    [cell.headImageButton addTarget:self action:@selector(clickHeadImageButton:) forControlEvents:UIControlEventTouchUpInside];
    HRLikeMeModel *model =[HRLikeMeModel getLikeMeModelWithDictionary:dic];
    if (model.img.length>0) {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; //显示最右边的箭头
    }else{
        cell.accessoryType = NO; //显示最右边的箭头

    }
    cell.model = model;
    
    

    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *dic = _dataSource[indexPath.row];
    HRLikeMeModel *model =[HRLikeMeModel getLikeMeModelWithDictionary:dic];

    if (model.img.length>0) {
        
        FriendLikeGitfAddController *vc = [[FriendLikeGitfAddController alloc] init];
        vc.model = model;
        [self.navigationController pushViewController:vc animated:YES];
        
    }else{
        
    }

}
//点击头像看资料
- (void)clickHeadImageButton:(UIButton *)sender {
    NSInteger index = sender.tag - 300;
    NSDictionary *dic = _dataSource[index];
    HRLikeMeModel *model = [HRLikeMeModel getLikeMeModelWithDictionary:dic];
    HomeStrangCollionViewController *UDIVC = [[HomeStrangCollionViewController alloc]init];
    
    UDIVC.UserId =  [NSString stringWithFormat:@"%ld",(long)model.wid];
    [self.navigationController pushViewController:UDIVC animated:YES];
}
//接受请求
- (void)clickLikeButton:(UIButton *)sender {
    [SVProgressHUD show];
    self.view.userInteractionEnabled = NO;
    NSInteger index = sender.tag - 100;
    NSDictionary *dic = _dataSource[index];
    HRLikeMeModel *model = [HRLikeMeModel getLikeMeModelWithDictionary:dic];
    WEAKSELF
    [HQHttpManager pickWooWithUid:[HQHttpManager getUserId] wid:@(model.wid) type:@(2) successBlock:^(BOOL isSuccess, NSDictionary *resultDic) {
        [SVProgressHUD dismiss];
        self.view.userInteractionEnabled = YES;
        if (isSuccess) {
            if (model.askId) {
                [HQHttpManager getAskByIdWithUid:[HQHttpManager getUserId] wid:@(model.wid) askId:@(model.askId) userGiftId:@(model.userGiftId) successBlock:^(BOOL isSuccess, NSDictionary *resultDic) {
                    weakSelf.pageNum = 1;
                    [weakSelf sendRequest];
                    HQConversationViewController *conversationVC = [[HQConversationViewController alloc]init];
                    conversationVC.conversationType = ConversationType_PRIVATE;
                    conversationVC.targetId = @(model.wid).stringValue;
                    conversationVC.title = model.nickName;
                    conversationVC.hidesBottomBarWhenPushed = YES;
                    [weakSelf.navigationController pushViewController:conversationVC animated:YES];
                }];
            } else {
                weakSelf.pageNum = 1;
                [weakSelf sendRequest];
                HQConversationViewController *conversationVC = [[HQConversationViewController alloc]init];
                conversationVC.conversationType = ConversationType_PRIVATE;
                conversationVC.targetId = @(model.wid).stringValue;
                conversationVC.title = model.nickName;
                [conversationVC sendMessage:[RCTextMessage messageWithContent:@"我们已经是好友了，可以尽情聊天了"] pushContent:@"friend"];
                conversationVC.hidesBottomBarWhenPushed = YES;
                [weakSelf.navigationController pushViewController:conversationVC animated:YES];
            }
        }
    }];
}
//拒绝请求
- (void)clickRefuseButton:(UIButton *)sender {
    [SVProgressHUD show];
    self.view.userInteractionEnabled = NO;
    NSInteger index = sender.tag - 200;
    NSDictionary *dic = _dataSource[index];
    HRLikeMeModel *model = [HRLikeMeModel getLikeMeModelWithDictionary:dic];
    WEAKSELF
    [HQHttpManager pickWooWithUid:[HQHttpManager getUserId] wid:@(model.wid) type:@(1) successBlock:^(BOOL isSuccess, NSDictionary *resultDic) {
        [SVProgressHUD dismiss];
        self.view.userInteractionEnabled = YES;
        if (isSuccess) {
            weakSelf.pageNum = 1;
            [weakSelf sendRequest];
        }
    }];
}

@end
